package com.wencai.controller;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.Arrays;

import static com.wencai.WenCai.getCurrentDayStock;

@RestController
public class WxController {

    private static final String TOKEN = "780cbba7a26e4fe0af938f43583c0b0b";
    private static final String aesKey = "POpUZt3tXiwXr1w6gKooh4vaHUokT2rdJG0qieX2WG8";

    @RequestMapping("/test")
    public String wencai() {
        String returnString = "";
        try {
            returnString = getCurrentDayStock();
        } catch (IOException | InterruptedException e) {
            returnString = e.getMessage();
        }
        return returnString;
    }

    /**
     * 处理用户消息（POST请求）
     */
    @PostMapping("/wx")
    @ResponseBody
    public String handleMessage(@RequestBody String xmlBody) throws Exception {
        // 解析XML消息
        Document document = DocumentHelper.parseText(xmlBody);
        Element root = document.getRootElement();

        String msgType = root.elementText("MsgType");
        String fromUser = root.elementText("FromUserName");
        String toUser = root.elementText("ToUserName");
        String content = root.elementText("Content");

        System.out.println("fromUser: " + fromUser);
        System.out.println("toUser: " + toUser);
        System.out.println("content: " + content);
        System.out.println("msgType: " + msgType);


        String returnString = "时间戳:"+System.currentTimeMillis()+System.lineSeparator();
        try {
            returnString = returnString + getCurrentDayStock();
        } catch (Exception e) {
            returnString = returnString + e.getMessage();
        }

        String result = buildTextReply(fromUser, toUser, returnString);
        System.out.println("result: " + result);
        return result;

//        // 根据消息类型生成回复
//        if ("text".equals(msgType)) {
//            String replyContent = "Received: " + content;
//            return buildTextReply(fromUser, toUser, replyContent);
//        }
//
//        return ""; // 默认返回空（不回复）
    }

    /**
     * 构建文本回复XML
     */
    private String buildTextReply(String fromUser, String toUser, String content) {
        return String.format(
                "<xml>" +
                        "<ToUserName><![CDATA[%s]]></ToUserName>" +
                        "<FromUserName><![CDATA[%s]]></FromUserName>" +
                        "<CreateTime>%d</CreateTime>" +
                        "<MsgType><![CDATA[text]]></MsgType>" +
                        "<Content><![CDATA[%s]]></Content>" +
                        "</xml>",
                fromUser, toUser, System.currentTimeMillis() / 1000, content);
    }

    @GetMapping("/wx")
    @ResponseBody
    public String verifyServer(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) {

        System.out.println("signature: " + signature);
        System.out.println("timestamp: " + timestamp);
        System.out.println("nonce: " + nonce);
        System.out.println("echostr: " + echostr);

        // 校验签名
        if (checkSignature(signature, timestamp, nonce)) {
            System.out.println("success:"+echostr);
            return echostr;
        } else {
            System.out.println("fail");
            return "Verification failed";
        }
    }

    /**
     * 校验微信签名
     */
    private boolean checkSignature(String signature, String timestamp, String nonce) {
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        String combined = String.join("", arr);

        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(combined.getBytes());
            String calculatedSignature = bytesToHex(digest);
            return calculatedSignature.equals(signature);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 字节数组转十六进制字符串
     */
    private String bytesToHex(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02x", b));
        }
        return hex.toString();
    }
}